#!/usr/bin/python
# -*- coding: UTF-8 -*-
"""
@author: zhangZW
@file: main.py
@time: 2023/01/19
@des: 注册客户端到CloudPlatform平台
"""
import os
import time

import requests
from scripts import tools
from pathlib import Path
import subprocess
import socket

sys_type = tools.get_system()

def register():
    secret = tools.readini().get('client', 'secret')
    ip = tools.readini().get('client', 'ip')
    port = tools.readini().getint('client', 'port')
    server_ip = tools.analyse_b64(secret).split(',')[1]
    server_port = tools.readini().getint('server', 'port')
    # server_ip = info_list[1]
    # client_info_list = tools.analyse_b64(info_list[0]).split(',')
    # 请求激活客户端
    res = requests.post(
        url=f'http://{server_ip}:{server_port}/client/register/',
        data={
            'ip': ip,
            'port': port,
            'secret': secret,
            'client_sys_type': tools.get_system()
        },
    )
    print(res.status_code)
    if res.status_code == 200:
        # data = res.json()
        # 激活设备成功！
        return 1
    elif res.status_code == 202:
        # 设备已激活，不能重复激活
        return 2
    else:
        # 出错
        return 0


def get_ip():
    return socket.gethostbyname(socket.gethostname())


def start():
    if register():
        if get_ip() == tools.readini().get('client', 'ip'):
            jar_path = Path.cwd().parent / 'lib' / 'selenium-server-4.5.2.jar'
            execute = f"java -jar {jar_path} standalone --host {tools.readini().get('client', 'ip')} --port {tools.readini().getint('client', 'port')}"
            # si = subprocess.STARTUPINFO()
            # si.dwFlags |= subprocess.STARTF_USESHOWWINDOW
            output = subprocess.Popen(execute, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                                      encoding='UTF-8')
            while output.poll() is None:
                out = output.stdout.readline()
                # outerr = output.stderr.readline()
                if out != b"":
                    print(out)
            if output.poll() is None:
                output.kill()
                print('End！')
        else:
            print('部分参数错误，请查看客户端配置文件。')
    else:
        print('设备链接远程服务失败，请查看配置文件后重新启动！')


if __name__ == '__main__':
    # print(get_ip())
    # print(type(get_ip()))
    start()